<!--
 * @Author: 卢景滔
 * @Date: 2021-12-20 17:21:11
 * @LastEditTime: 2021-12-22 09:41:41
 * @LastEditors: 卢景滔
 * @Description: SharedWorker使用
-->
<template>
  <div><h1>SharedWorker使用</h1></div>
</template>

<script>
export default {
  created() {
    // 兼容性判断
    if (!window.SharedWorker) {
      throw new Error('当前浏览器不支持SharedWorker')
    }

    // 创建共享线程
    this.worker = new SharedWorker('/shared-worker/SharedWorker.js')

    // 启动线程端口
    this.worker.port.start()

    // 向共享线程发送消息
    this.worker.port.postMessage('counter++')

    // 线程监听消息
    this.worker.port.addEventListener('message', this.messageHandle)
  },
  methods: {
    // 消息处理
    messageHandle(e) {
      console.log('SharedWorker共享线程counter值：', e.data)
    },
  },
  destroyed() {
    // 记得销毁线程
    this.worker.port.removeEventListener('message', this.messageHandle)
    this.worker.port.close()
    this.worker = null
  },
}
</script>
